package com.csi.controller.user;

import com.alibaba.fastjson2.JSON;
import com.csi.domain.User;
import com.csi.pojo.Result;
import com.csi.service.UserService;
import com.csi.service.impl.UserServiceImpl;
import com.csi.utils.DateStringFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@WebServlet("/user/updateAllInfoController")
public class UpdateAllInfoController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置响应内容类型
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        // 获取请求参数
        int userId = 0;
        try {
            userId = Integer.parseInt(req.getParameter("userId"));
        } catch (NumberFormatException e) {
            Result<String> result = new Result<>();
            result.setCode(400);
            result.setMsg("userId不正确");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String borndate = req.getParameter("borndate");
        String gender = req.getParameter("gender");
        String homeAddress = req.getParameter("home_address");
        String companyAddress = req.getParameter("company_address");
        String englishName = req.getParameter("englishName");

        // 判断邮箱格式是否正确
        if (!email.matches("^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
            Result<String> result = new Result<>();
            result.setCode(400);
            result.setMsg("邮箱格式不正确");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        // 判断英文名格式
        if (!englishName.matches("^[a-zA-Z ]+$")) {
            Result<String> result = new Result<>();
            result.setCode(400);
            result.setMsg("输入不是英文");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        // 判断联系电话格式是否正确
        if (!phone.matches("^1[3456789]\\d{9}$")) {
            Result<String> result = new Result<>();
            result.setCode(400);
            result.setMsg("联系电话格式不正确");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        // 判断手机号是否已存在
        UserService userService = new UserServiceImpl();
        try {
            List<User> userList = userService.findAll();
            for (User u : userList) {
                // 判断当前用户的手机号是否与修改后的手机号一致
                if (u != null && u.getPhone() != null && u.getPhone().equals(phone) && u.getUserId() != userId) {
                    Result<String> result = new Result<>();
                    result.setCode(401);
                    result.setMsg("该手机号已被注册");
                    out.print(JSON.toJSONString(result));
                    out.flush();
                    out.close();
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = new Result<>();
            result.setCode(500);
            result.setMsg("查询手机号失败");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        // 判断生日格式是否正确
        if (!borndate.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
            Result<String> result = new Result<>();
            result.setCode(400);
            result.setMsg("生日格式不正确");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        // 判断生日是否小于当前日期
        Date currentDate = new Date();
        Date selectedDate = DateStringFormat.string2Date(borndate);
        if (selectedDate.compareTo(currentDate) > 0) {
            Result<String> result = new Result<>();
            result.setCode(400);
            result.setMsg("生日不能大于当前日期");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }


        // 创建User对象
        User user = userService.findById(userId);
        user.setCompanyAddress(companyAddress);
        user.setHomeAddress(homeAddress);
        user.setPhone(phone);
        user.setEmail(email);
        user.setGender(gender);
        user.setEnglishName(englishName);
        user.setBorndate(DateStringFormat.string2Date(borndate));

        try {
            userService.updateAllInfo(user);
            Result<String> result = new Result<>();
            result.setCode(200);
            result.setMsg("success");

            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = new Result<>();
            result.setCode(500);
            result.setMsg("fail");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }
}
